package com.abel.bigwater.tlv.model

import io.netty.buffer.ByteBuf
import org.slf4j.LoggerFactory
import kotlin.experimental.and

class TlvData4Warn(
        var maxFlowWarn: ByteArray? = null,
        var dataTamper: Short = 0,
        var revertFlow: Short = 0,
        var maganetic: Short = 0,
        var internalError: Short = 0,
        var remoteDetached: Short = 0) : TlvData(tag = WarnParam.TAG) {
    override fun fill(buf: ByteBuf): ByteBuf {
        if (length == 0) finalLen()

        with(buf.alloc().buffer())
        {
            writeByte(WarnParam.T1MaxFlowWarn.id.toInt())
            writeBytes(maxFlowWarn)

            writeByte(WarnParam.T2DataTamper.id.toInt())
            writeByte(dataTamper.toInt())

            writeByte(WarnParam.T3RevertWarn.id.toInt())
            writeByte(revertFlow.toInt())

            writeByte(WarnParam.T4Magnetic.id.toInt())
            writeByte(maganetic.toInt())

            writeByte(WarnParam.T5InternalError.id.toInt())
            writeByte(internalError.toInt())

            writeByte(WarnParam.T6RemoteDetach.id.toInt())
            writeByte(remoteDetached.toInt())

            buf.writeBytes(this)
        }

        return buf
    }

    override fun parse(buf: ByteBuf): ByteBuf {
        var ret: ByteBuf? = null
        try {
            ret = super.parse(buf)
        } catch (ex: Exception) {
            log.error("Fail to parse Tlv-data-warn caused by ${ex.message}", ex)
        }

        for (p1 in pieceList) {
            when (p1.id) {
                WarnParam.T1MaxFlowWarn.id -> {
                }

                WarnParam.T2DataTamper.id -> dataTamper = p1.readByte()

                WarnParam.T3RevertWarn.id -> revertFlow = p1.readByte()

                WarnParam.T4Magnetic.id -> maganetic = p1.readByte()

                WarnParam.T5InternalError.id -> internalError = p1.readByte()

                WarnParam.T6RemoteDetach.id -> remoteDetached = p1.readByte()
            }
        }

        return ret!!
    }
}